package es.udc.emarketapp.emarket.model.categoryFacade.actions;

import es.udc.emarketapp.emarket.model.category.dao.SQLCategoryDAO;
import es.udc.emarketapp.emarket.model.category.dao.SQLCategoryDAOFactory;
import es.udc.emarketapp.emarket.model.category.vo.CategoryVO;
import java.sql.Connection;
import java.util.List;

import es.udc.emarketapp.emarket.model.product.dao.SQLProductDAO;
import es.udc.emarketapp.emarket.model.product.dao.SQLProductDAOFactory;
import es.udc.emarketapp.emarket.model.product.vo.ProductVO;
import es.udc.emarketapp.emarket.model.productFacade.vo.ProductChunkVO;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.sql.NonTransactionalPlainAction;

public class FindByCategoryAction implements NonTransactionalPlainAction {

	private Long idCat;
	private int startIndex;
	private int count;

	public FindByCategoryAction(Long idCat, int startIndex, int count) {
		
		this.idCat = idCat;
		this.startIndex = startIndex;
		this.count = count;
    
	}

	/**
	 *
	 * @return An instance of <code>ProductChunkVO</code> objects.
	 */
	public Object execute(Connection connection) 
		throws InternalErrorException {

		/* 
		 * Find count+1 products to determine if there exist more products
		 * above the specified range.
		 */                
		SQLProductDAO productDAO = SQLProductDAOFactory.getDAO();

		List<ProductVO> productVOs = productDAO.findByCategory(
				connection, idCat, 5, startIndex, count+1);

                boolean existMoreProducts = productVOs.size() == (count+1);

		/* 
		 * Remove the last account from the returned list if there exist more
		 * accounts above the specified range.
		 */
		if (existMoreProducts) {
			productVOs.remove(productVOs.size()-1);
		}

		return new ProductChunkVO(productVOs, existMoreProducts);                    

	}


}